﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApp.Models;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace WebApp.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AsyncProductsController : ControllerBase
    {
        private DataContext dbContext;

        public AsyncProductsController(DataContext dbContext)
        {
            this.dbContext = dbContext;
        }

        [HttpGet]
        public IAsyncEnumerable<Product> GetProducts()
        {
            return dbContext.Products;
        }

        [HttpGet("{id}")]
        public async Task<Product> GetProduct(long id)
        { 
            return await dbContext.Products.FindAsync(id);
        }

        [HttpPost]
        public async Task AddProduct([FromBody] ProductBinding p)
        {
            await dbContext.Products.AddAsync(p.ToProudct());
            await dbContext.SaveChangesAsync();
        }

        [HttpPut]
        public async Task UpdateProduct([FromBody] Product p)
        {
            dbContext.Update(p);
            await dbContext.SaveChangesAsync();
        }

        [HttpDelete("{id}")]
        public async Task DeleteProduct(long id)
        {
            dbContext.Products.Remove(new Product() { ProductId = id });
            await dbContext.SaveChangesAsync();
        }
    }
}
